<template>
  <div class="comment-post">
    <van-field
      class="post-field"
      v-model="message"
      rows="2"
      autosize
      type="textarea"
      maxlength="50"
      placeholder="请输入留言"
      show-word-limit
    />
    <van-button class="post-btn" @click="postComment">发布</van-button>
  </div>
</template>

<script>
import { addPostComment } from '@/api/comment'
export default {
  name: 'CommentPost',
  components: {},
  props: ['target'],
  data () {
    return {
      message: ''
    }
  },
  inject: {
    articleId: {
      type: [Number, String, Object],
      default: null
    }
  },
  computed: {},
  watch: {},
  created () {},
  mounted () {},
  methods: {
    async postComment () {
      this.$toast.loading({
        message: '发布中...',
        forbidClick: true, // 禁止背景点击
        duration: 0 // 展示时长(ms)，值为 0 时，toast 不会消失
      })

      if (this.message.trim().length === 0) {
        return this.$toast('评论内容不能为空！')
      }
      try {
        const res = await addPostComment({
          target: this.target,
          content: this.message,
          art_id: this.articleId ? this.articleId.toString() : null
        })
        console.log(res)
        this.$toast('评论成功！')
        // 通知父组件关闭弹层
        this.$emit('closePopup')
        // 清空输入框
        this.message = ''
        // 通知父组件更新评论列表
        this.$emit('unshiftList', res.data.data.new_obj)
      } catch (error) {
        this.$toast('发布失败，请稍后再试！')
      }
    }
  }
}
</script>

<style scoped lang="less">
.comment-post {
  display: flex;
  align-items: center;
  padding: 32px 0 32px 32px;
  .post-field {
    background-color: #f5f7f9;
  }
  .post-btn {
    width: 150px;
    border: none;
    padding: 0;
    color: #6ba3d8;
    &::before {
      display: none;
    }
  }
}
</style>
